#include "archiv.h"
#include "ui_archiv.h"

Archiv::Archiv(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Archiv)
{
    ui->setupUi(this);

    db = QSqlDatabase::database();

    connect(ui->archiv_table, SIGNAL(itemSelectionChanged()), SLOT(showRemi()));
    connect(ui->archiv_table, SIGNAL(itemSelectionChanged()), SLOT(checkPrint()));
    connect(ui->print_button, SIGNAL(clicked()), SLOT(printRemi()));
}

Archiv::~Archiv()
{
    delete ui;
}

/*========== SLOTS ========== */

void Archiv::reloadArchive()
{
    if ( db.open() )
    {
        ui->archiv_table->blockSignals(true);
        ui->archiv_table->setSortingEnabled(false);
        ui->archiv_table->clearContents();
        ui->archiv_table->setRowCount(0);

        QSqlQuery q(QLatin1String("SELECT archiv.id, archiv.datetime, (SELECT COUNT(*) FROM remission WHERE archiv_id=archiv.id) AS erfassungen, (SELECT SUM(menge*preis) FROM remission WHERE archiv_id=archiv.id) AS summe FROM archiv ORDER BY archiv.datetime DESC;"), db);
        while ( q.next() )
        {
            QTableWidgetItem *tab_datum = new QTableWidgetItem( q.value(1).toDateTime().toString("dd.MM.yy hh:mm") );
            QTableWidgetItem *tab_erfassungen = new QTableWidgetItem( q.value(2).toString() );
            QTableWidgetItem *tab_summe = new QTableWidgetItem(QString("%L1 €").arg(q.value(3).toDouble(),0,'f',2));

            tab_datum->setData(Qt::UserRole, q.value(0));
            tab_datum->setData(Qt::UserRole+1, q.value(1));
            tab_summe->setData(Qt::UserRole, q.value(3));

            ui->archiv_table->insertRow( ui->archiv_table->rowCount() );
            ui->archiv_table->setItem( ui->archiv_table->rowCount()-1, 0, tab_datum );
            ui->archiv_table->setItem( ui->archiv_table->rowCount()-1, 1, tab_erfassungen );
            ui->archiv_table->setItem( ui->archiv_table->rowCount()-1, 2, tab_summe );
        }

        ui->archiv_table->resizeColumnsToContents();
        ui->archiv_table->setSortingEnabled(false); /** Sortierung vorerst deaktiviert, da nach Tagen sortiert wird. ToDo: eigenes Table-Model **/
        //ui->archiv_table->sortByColumn(0, Qt::AscendingOrder);

        ui->archiv_table->blockSignals(false);
    }
}

void Archiv::showRemi()
{
    if ( !ui->archiv_table->selectedItems().isEmpty() && db.open() )
    {
        ui->remi_table->scrollToTop();
        ui->remi_table->setSortingEnabled(false);
        ui->remi_table->clearContents();
        ui->remi_table->setRowCount(0);

        QSqlQuery q(QLatin1String("SELECT `id`, `titel`, `gtin`, `addon`, `menge`, `datetime`, `paket_id`, `preis` FROM `remission` WHERE `archiv_id` = '") + ui->archiv_table->selectedItems().at(0)->data(Qt::UserRole).toString() + QLatin1String("' ORDER BY `datetime` ASC;"), db);
        while ( q.next() )
        {
            QList<QTableWidgetItem*> remi;
            remi.append(new QTableWidgetItem(q.value(1).toString()));
            remi.append(new QTableWidgetItem(da.getAusgabe(q.value(2).toString(), q.value(3).toString())));
            remi.append(new QTableWidgetItem(QString("%L1 €").arg(q.value(7).toFloat(),0,'f',2)));
            remi.append(new QTableWidgetItem(q.value(4).toString()));
            remi.append(new QTableWidgetItem(QString("%L1 €").arg(q.value(4).toInt() * q.value(7).toFloat(),0,'f',2)));
            remi.append(new QTableWidgetItem(QDateTime::fromString(q.value(5).toString(), "yyyy-MM-dd hh:mm:ss.zzz").toString("dd.MM.yy hh:mm")));
            remi.append(new QTableWidgetItem(q.value(2).toString()));
            remi.append(new QTableWidgetItem(q.value(3).toString()));
            remi.append(new QTableWidgetItem(q.value(6).toString()));

            remi[2]->setTextAlignment(Qt::AlignRight);
            remi[3]->setTextAlignment(Qt::AlignHCenter);
            remi[4]->setTextAlignment(Qt::AlignRight);
            remi[8]->setTextAlignment(Qt::AlignHCenter);

            ui->remi_table->insertRow( ui->remi_table->rowCount() );
            int col = 0;
            foreach ( QTableWidgetItem *i, remi )
            {
                i->setFlags(Qt::ItemIsEnabled|Qt::ItemIsSelectable);
                ui->remi_table->setItem( ui->remi_table->rowCount()-1, col++, i );
            }
        }

        ui->remi_table->setSortingEnabled(true);
        ui->remi_table->sortByColumn(7, Qt::AscendingOrder); /** Nach Addon-Code sortieren **/
        ui->remi_table->sortByColumn(0, Qt::AscendingOrder); /** Nach Titel sortieren **/
        ui->remi_table->sortByColumn(8, Qt::AscendingOrder); /** Nach Paket sortieren **/
        ui->remi_table->resizeColumnsToContents();
    }
}

void Archiv::checkPrint()
{
    ui->print_button->setEnabled( ui->archiv_table->selectedItems().isEmpty()?false:true );
}

void Archiv::printRemi()
{
    if ( !ui->archiv_table->selectedItems().isEmpty() )
    {
        QTextEdit *te = new QTextEdit();

        QString content;
        content.append(QLatin1String("<html><head><title>Remission vom ") + ui->archiv_table->selectedItems().at(0)->data(Qt::UserRole+1).toDateTime().toString("dd.MM.yy hh:mm") + QLatin1String("</title></head>"));
        content.append(QLatin1String("<body><h1 align=\"center\" style=\"font-size:x-large;\">") + tr("Remission vom ") + ui->archiv_table->selectedItems().at(0)->data(Qt::UserRole+1).toDateTime().toString("dd.MM.yy hh:mm") + QLatin1String("</h1><table width=\"100%\"><thead><tr><th>") + tr("Titel") + QLatin1String("</th><th>") + tr("Ausgabe") + QLatin1String("</th><th>") + tr("Preis") + QLatin1String("</th><th>") + tr("Menge") + QLatin1String("</th><th>") + tr("Summe") + QLatin1String("</th><th>") + tr("Paket") + QLatin1String("</th></tr></thead><tbody>"));

        for ( int i=0; i < ui->remi_table->rowCount(); i++ )
        {
            content.append(QLatin1String("<tr>"));
            content.append(QLatin1String("<td>") + ui->remi_table->item(i, 0)->text() + QLatin1String("</td>"));
            content.append(QLatin1String("<td>") + ui->remi_table->item(i, 1)->text() + QLatin1String("</td>"));
            content.append(QLatin1String("<td align=\"right\">") + ui->remi_table->item(i, 2)->text() + QLatin1String("</td>"));
            content.append(QLatin1String("<td align=\"center\">") + ui->remi_table->item(i, 3)->text() + QLatin1String("</td>"));
            content.append(QLatin1String("<td align=\"right\">") + ui->remi_table->item(i, 4)->text() + QLatin1String("</td>"));
            content.append(QLatin1String("<td align=\"center\">") + ui->remi_table->item(i, 8)->text() + QLatin1String("</td>"));
            content.append(QLatin1String("</tr>"));
        }

        content.append(QLatin1String("</tbody></table></body></html>"));

        te->setHtml(content);

        QPrinter *printer = new QPrinter(QPrinter::HighResolution);
        QPrintDialog printDialog(printer);
        if (printDialog.exec() == QDialog::Accepted)
        {
            te->print(printer);
        }
    }
}

void Archiv::markFirstRemi()
{
    ui->archiv_table->setCurrentCell(0,0);
}
